package com.zhx.demo.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

/**
 * security userdetailservice 实现类
 *
 * security 中获取用户信息的实现
 *
 * 需要继承 UserDetailsService 接口 实现 loadUserByUsername方法
 *
 * 此方法 需要自己实现   通过自己查询数据等获取用户信息
 *
 * 如果没有找到用户就会返回  UsernameNotFoundException  用户查找不到的错误
 *
 * @author zhx
 * @create 2017-11-02 9:23
 **/
@Component("myUserDetailService")
public class MyUserDetailService  implements UserDetailsService,SocialUserDetailsService{

    private  final static Logger logger = LoggerFactory.getLogger(MyUserDetailService.class);


    //注入springsecurity 密码加密逻辑  PasswordEncoder  spring自动加密密码并且加盐  每次登陆都不一样
    @Autowired
    private PasswordEncoder passwordEncoder;

    //在此接口中去查找用户  自己注入自己的用户查找方法   需要返回一个 UserDetails 对象  这个对象是springssecurity中的用户对象
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        logger.info("loadUserByUsername 中获取的用户名是:{}",s);
        //AuthorityUtils.commaSeparatedStringToAuthorityList 方法 截取字符串根据逗号并且返回springsecurity 的 GrantedAuthority对象

        //List<GrantedAuthority> admin = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
        //简单的UserDetail返回
        //return new User(s,"123456", AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));

        return buildUser(s);
    }

    /**
     * spring social 需要实现的查找用户的方法
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public SocialUserDetails loadUserByUserId(String s) throws UsernameNotFoundException {
        logger.info("loadUserByUserId 中获取的用户ID是:{}",s);

        return buildUser(s);
    }


    private SocialUserDetails buildUser(String userId){
        String password = passwordEncoder.encode("123456");
        logger.info("数据库密码是:"+password);

        return  new SocialUser(userId,password,true,true,true,true,AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
